package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQueryDTO;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveOrUpdateParamDTO;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class VehicleServiceImpl  implements VehicleService {

    @Autowired
    VehicleMapper vehicleMapper;

    /**处理页面发出的： 查询车辆信息的请求的方法*/
    public List<VehicleVO> selectVehicle(VehicleQueryDTO vehicleQuery) {
        log.info("VehicleServiceImpl-查询所有车辆的方法selectVehicle,查询条件{}",vehicleQuery);
        List<VehicleVO> list=vehicleMapper.selectVehicles(vehicleQuery);
        log.info("VehicleServiceImpl-查询所有车辆的方法selectVehicle,查询结果{}",list);
        return list;
    }


    /**处理页面发出的： 保存一个车辆信息的请求的方法*/
    public String saveOrUpdateVehicle(VehicleSaveOrUpdateParamDTO vehicleSaveOrUpdateParamDTO) {
        log.info("VehicleServiceImpl-保存一个车辆信息的请求的方法saveOrUpdateVehicle(),保存的数据{}",vehicleSaveOrUpdateParamDTO);
        Vehicle vehicle=new Vehicle();
        //用spring提供的工具类BeanUtils的copyProperties方法，将vehicleSaveParam中的数据复制到vehicle中
        BeanUtils.copyProperties(vehicleSaveOrUpdateParamDTO,vehicle);
        if(vehicle.getId()==null){
            vehicle.setCreateTime(new Date());
            vehicle.setStatus("1");//默认车辆状态为空闲
            vehicleMapper.insertVehicle(vehicle);
            return "车辆新增成功";
        }else{
            vehicle.setUpdateTime(new Date());
            vehicleMapper.updateVehicle(vehicle);
            return "车辆修改成功";
        }

    }

    public void deleteVehicle(Long vehicleId) {
        log.info("VehicleServiceImpl-根据车辆id，从mysql中删除车辆信息的方法deleteVehicle(),车辆id{}"+vehicleId);
        vehicleMapper.deleteVehicle(vehicleId);
    }

    public void unbindVehicle(Long vehicleId) {
        log.debug("VehicleServiceImpl-解除当前电子围栏绑定的车辆编号为:{}的车辆信息"+vehicleId);
        Vehicle vehicle=new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceBindStatus("0");
        //之前的update相关的SQL的if判断要求部位null的值才更新
        //但这里的业务是要将车辆的围栏id更新为null，所以需要重新编写一个方法
        vehicle.setGeofenceId(null);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.updateNullGeofenceId(vehicle);

    }

    public void bindVehicle(Long geofenceId, Long vehicleId) {
        Vehicle vehicle=new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceId(geofenceId);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.updateVehicle(vehicle);
    }
}
